package com.cskaoyan.realm;

import com.cskaoyan.bean.ActiveUser;
import com.cskaoyan.bo.system.AdminCreateBo;
import com.cskaoyan.mapper.AdminMapper;
import com.cskaoyan.mapper.PermissionMapper;
import com.cskaoyan.token.MallToken;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    PermissionMapper permissionMapper;

    // 认证：en
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        // TODO:从数据库中查
        String pswFromDB = adminMapper.selectPswByUsername(username);
        ActiveUser activeUser = new ActiveUser();
        activeUser.setUsername(username);

        // 第三个参数是realm的名字，不重要
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(activeUser, pswFromDB, this.getName());
        return authenticationInfo;
    }

    // 授权：or
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();

        // 去数据库中查出permissions
        AdminCreateBo adminCreateBo = adminMapper.selectTempInfo(activeUser.getUsername());
        List<String> perms = permissionMapper.selectPermByRids(adminCreateBo.getRoleIds());
        if (perms.contains("*")){
            perms=permissionMapper.seletSuperAdminPerms();
        }


        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(perms);
        return authorizationInfo;
    }

}
